package com.qf.openapi.web.master.interceptor;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AutologinInterceptor implements HandlerInterceptor {
    UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断User是否已经登录
        final HttpSession session = request.getSession();
        final User u = (User) session.getAttribute(Constants.USER_SESSION_KEY);
        if (u!=null){
            response.sendRedirect("/index.html");
            return false;
        }

        final Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            final String name = cookie.getName();
            if(name.equals(Constants.USER_AUTOLOGIN_TOKEN)){
                final String value = cookie.getValue();
                final String[] split = value.split("-");
                final String username = split[0];
                final String password = split[1];
                User user = userService.login(username, password);
                if(user!=null){
//                    final HttpSession session = request.getSession();
                    session.setAttribute(Constants.USER_SESSION_KEY,user);
                    response.sendRedirect("/index.html");
                    return false;
                }
            }
        }
        return true;
    }
}
